import {
  Color,
  Math,
  Cartesian3,
  createWorldTerrain,
  Ion,
  Viewer,
  PolylineOutlineMaterialProperty,
  Cartesian2,
} from "cesium";
import { Menu } from "../ui/menu";

(window as any).CESIUM_BASE_URL = ".";
Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0ZThhOTZlNS05MzgwLTRkNTYtODc1Yy01MTYwMzI3NWUyZmIiLCJpZCI6MjQzNzcsImlhdCI6MTY1NjU1MjkzMH0.XzOOAtPz4ZcVQiQxo5BG5gbeVWtdmTtgwa-5MjCl7-s";

let mapDom = document.createElement("div");
mapDom.style.width = "100vw";
mapDom.style.height = "100vh";
mapDom.id = "app";
document.body.appendChild(mapDom);

let viewer = new Viewer("app", {
  terrainProvider: createWorldTerrain(),
  shouldAnimate: true,
});

viewer.scene.canvas.addEventListener(
  "click",
  (event) => {
    event.preventDefault();
    const mousePosition = new Cartesian2(event.clientX, event.clientY);
    const selectedLocation = convertScreenPixelToLocation(mousePosition);
	console.log([selectedLocation.lng, selectedLocation.lat]);
  },
  false
);

function convertScreenPixelToLocation(mousePosition) {
  const ellipsoid = viewer.scene.globe.ellipsoid;
  const cartesian = viewer.camera.pickEllipsoid(mousePosition, ellipsoid);
  if (cartesian) {
    const cartographic = ellipsoid.cartesianToCartographic(cartesian);
    const longitudeString = Math.toDegrees(cartographic.longitude).toFixed(15);
    const latitudeString = Math.toDegrees(cartographic.latitude).toFixed(15);
    return { lat: Number(latitudeString), lng: Number(longitudeString) };
  } else {
    return null;
  }
}

let menu = new Menu();
let entities = viewer.entities;
let camera = viewer.camera;
menu.createElement("button", "add line", () => {
  let line = entities.add({
    polyline: {
      positions: Cartesian3.fromDegreesArray([
        86.953793, 27.928257, 86.953793, 27.988257, 86.896497, 27.988257,
      ]),
      clampToGround: true,
      width: 10,
      material: new PolylineOutlineMaterialProperty({
        color: Color.YELLOW,
        outlineWidth: 2,
        outlineColor: Color.RED,
      }),
    },
  });
  // @ts-ignore
  window.camara = camera;

  camera.flyTo({
    destination: Cartesian3.fromDegrees(87.04517960577803, 27.97210671428214, 20000),
    //   orientation: {
    // 	  heading: Math.toRadians(0),
    // 	  pitch: Math.toRadians(-90),
    // 	  roll: Math.toRadians(0)
    //   }
    orientation: {
      direction: new Cartesian3(
        0.627104044243983,
        -0.7152522508696093,
        -0.3084716118523683
      ),
      up: new Cartesian3(
        0.7732646692711458,
        0.5239428076388741,
        0.35713538830600305
      ),
    },
  });
});
